package cn.demengsite.base;

import cn.demengsite.dao.MemberDAO;
import cn.demengsite.dao.OrderDAO;
import cn.demengsite.dao.ProductDAO;
import cn.demengsite.dao.ReportDAO;
import cn.demengsite.model.Member;
import cn.demengsite.model.Order;
import cn.demengsite.model.Product;
import cn.demengsite.model.Report;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import tech.ideashare.utils.IS_ListUtils;
import tech.ideashare.utils.is_mail.IS_MailConfig;
import tech.ideashare.utils.is_mail.IS_MailUtils;
import tech.ideashare.utils.is_sms.IS_SMSConfig;
import tech.ideashare.utils.is_sms.IS_SMSUtils;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

import static cn.demengsite.base.ProductConfig.productNameMap;

@Component
public class EmailTask {

    @Autowired
    private OrderDAO orderDAO;

    @Autowired
    private MemberDAO memberDAO;

    @Autowired
    private ReportDAO reportDAO;

    @Autowired
    private  ProductDAO productDAO;

    @Scheduled(cron = "0 30 20 * * *")
    public void sendEmailByDay(){
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        String today  = format.format(new Date());
        //String today = "2017-11-15";
        StringBuffer sb  = new StringBuffer("");

        //获得今天所有的订单
        List<Order> todayOrders = orderDAO.getOrdersByTime(today,today);

        List<Report> todayDemengs = reportDAO.getSaleReportWithBeginEnd(today,today);
        if(todayDemengs!=null && todayDemengs.size()>0){
            //获得今天的充值总金额
            double totalCharge = todayOrders.stream().filter(o->o.getOrderStatus()==3).mapToDouble(Order::getTotalPrice).sum();
            //获得今天总营业额(不包含充值)
            double totalSale = todayDemengs.stream().mapToDouble(Report::getSalePrice).sum();
            //获得今天总件数
            long totalCount = todayDemengs.stream().count();
            //获取今天新办的会员
            List<Member> members = memberDAO.getMemberByCreateTime(today,today);
            long newMemberCount = members.stream().count();
            //老会员回头数
            long oldMember = todayOrders.stream().filter(o->o.getOrderStatus()!=3 && o.getMemberId()!=0).filter(IS_ListUtils.distinctByKey(Order::getMemberId)).count()-newMemberCount;



            sb.append(today).append("\n");
            sb.append("新.会.员：").append(newMemberCount).append("人\n");
            sb.append("老.会.员：").append(oldMember).append("人\n");
            sb.append("充值：").append(totalCharge).append("元\n");
            sb.append("总营业额（不含充值）:").append(totalCount).append("件，").append(totalSale).append("元\n");
        }else {
            sb.append("今天行情不好，请明天再看");
        }
        IS_SMSConfig config = new IS_SMSConfig();
        config.setKey("2cfb8ee9e6fc7034f8f1");
        config.setUid("lixiang9409");
        config.setUrl("http://utf8.api.smschinese.cn/");
//        IS_SMSUtils.sendSms(config,"18162300251",sb.toString());
        IS_SMSUtils.sendSms(config,"17740899943",sb.toString());

        //下面是库存和总的信息，只在邮件里面发送
        List<Member> members = memberDAO.getAllMember();
        //过滤掉测试的手机号
        members = members.stream().filter(m -> !m.getMemberMobile().equals("0")).collect(Collectors.toList());

        //总充值金额
        double sumRecharge = members.stream().mapToDouble(Member::getMemberCash).sum();

        //会员总数
        int totalNum = members.size();

        sb.append("总会员数：").append(totalNum).append("人\n");
        sb.append("总充值数：").append(sumRecharge).append("元\n");


        //总库存
        List<Product> products = productDAO.getAllProduct();

        //去除库存为0的数据和预留的会员卡数据
        List<Product> allProducts = products.stream().filter(p-> p.getProductNum()>0&&!p.getBarCode().startsWith("9")).collect(Collectors.toList());




        //计算各个款的总数
        Map<String ,String> styleMap = productNameMap;

        Map<String ,List<Product>> styleProductMap = new HashMap<>();

        for (String s : styleMap.keySet()) {
            List<Product> list = new ArrayList<>();
            styleProductMap.put(styleMap.get(s),list);
        }
        //秋一和秋二
        int auton1 =0;
        int auton2 =0;

        // 19年春款和夏款的数量
        int spring19 = 0;
        int summer19 = 0;

        //19年秋款
        int auton19 = 0;

        for (Product product : allProducts) {
            if(product.getBarCode().substring(1,3).equals("83")){
                auton1++;
            }else if(product.getBarCode().substring(1,3).equals("91")){
                spring19++;
            }else if(product.getBarCode().substring(1,3).equals("92")){
                summer19++;
            }else if(product.getBarCode().substring(1,3).equals("93")){
                auton19++;
            }


            for (String s : styleMap.keySet()) {
                if (product.getBarCode().substring(4,6).equals(s)) {
                    styleProductMap.get(styleMap.get(s)).add(product);
                }
            }
        }

        Map<String , Integer> styleNum = new HashMap<>();

        for (String s : styleProductMap.keySet()) {
            styleNum.put(s,styleProductMap.get(s).size());
        }

        sb.append("18年秋款还剩：").append(auton1).append("\n");
        sb.append("19年春款还剩：").append(spring19).append("\n");
        sb.append("19年夏款还剩：").append(summer19).append("\n");
        sb.append("19年秋款还剩：").append(auton19).append("\n");
        sb.append("其他的库存总计：").append(styleNum).append("\n");

        sb.append("本邮件由系统自动生成，请不要回复");

        String subject = "汉南德蒙斯特销售日况"+today;

        IS_MailConfig mailConfig = new IS_MailConfig("smtp.mxhichina.com",25,"tongzhuang@ideashare.tech","DeMeng888");
        mailConfig.setReceiverAddr("lixiang9409@vip.qq.com");
        IS_MailUtils.sendSimpleBySMTP(mailConfig,subject,sb.toString());

    }

}
